import time
import logging
from django.utils.deprecation import MiddlewareMixin
from django.contrib.auth.models import AnonymousUser
from .models import RequestLog

logger = logging.getLogger(__name__)


class RequestTimingMiddleware(MiddlewareMixin):
    """请求耗时统计中间件"""
    
    def process_request(self, request):
        """在请求开始时记录时间戳"""
        request.start_time = time.time()
        return None
    
    def process_response(self, request, response):
        """在响应结束时计算耗时并记录"""
        try:
            # 计算请求耗时（毫秒）
            if hasattr(request, 'start_time'):
                duration_ms = (time.time() - request.start_time) * 1000
            else:
                duration_ms = 0
            
            # 获取客户端IP地址
            ip_address = self.get_client_ip(request)
            
            # 获取用户（如果已认证）
            user = request.user if hasattr(request, 'user') and not isinstance(request.user, AnonymousUser) else None
            
            # 获取User-Agent
            user_agent = request.META.get('HTTP_USER_AGENT', '')
            
            # 记录请求日志
            try:
                RequestLog.objects.create(
                    path=request.get_full_path(),
                    method=request.method,
                    duration_ms=duration_ms,
                    status_code=response.status_code,
                    user=user,
                    ip_address=ip_address,
                    user_agent=user_agent
                )
            except Exception as e:
                # 如果记录日志失败，不要影响正常响应
                logger.error(f"Failed to log request: {str(e)}")
            
            # 在响应头中添加耗时信息
            response['X-Response-Time'] = f'{duration_ms:.2f}ms'
            
            # 如果耗时较长，记录警告日志
            if duration_ms > 1000:  # 超过1秒
                logger.warning(f"Slow request: {request.method} {request.get_full_path()} "
                             f"took {duration_ms:.2f}ms")
                
        except Exception as e:
            logger.error(f"Error in RequestTimingMiddleware: {str(e)}")
        
        return response
    
    def get_client_ip(self, request):
        """获取客户端真实IP地址"""
        # 尝试从各种代理头中获取真实IP
        x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
        if x_forwarded_for:
            # X-Forwarded-For可能包含多个IP，取第一个
            ip = x_forwarded_for.split(',')[0].strip()
            return ip
        
        x_real_ip = request.META.get('HTTP_X_REAL_IP')
        if x_real_ip:
            return x_real_ip
        
        # 如果没有代理头，使用REMOTE_ADDR
        return request.META.get('REMOTE_ADDR', '0.0.0.0')


class RequestStatisticsMiddleware(MiddlewareMixin):
    """请求统计中间件 - 可选的扩展功能"""
    
    def __init__(self, get_response):
        self.get_response = get_response
        # 内存中的简单计数器（生产环境中应使用Redis等）
        self.request_count = 0
        self.error_count = 0
        super().__init__(get_response)
    
    def process_request(self, request):
        """统计请求数量"""
        self.request_count += 1
        
        # 每1000个请求输出一次统计信息
        if self.request_count % 1000 == 0:
            logger.info(f"Processed {self.request_count} requests, {self.error_count} errors")
        
        return None
    
    def process_response(self, request, response):
        """统计错误响应"""
        if response.status_code >= 400:
            self.error_count += 1
        
        return response
